import React, { useState,useEffect } from 'react';
import {
  UserOutlined,
  SearchOutlined
} from '@ant-design/icons';
import { Layout, List,  Menu, Button, theme, ConfigProvider, Avatar,  FloatButton,AutoComplete,Space} from 'antd';
import {Input} from 'antd'
import { Route,Redirect,useHistory } from 'react-router-dom/cjs/react-router-dom.min';
import Post from '../components/Post';
import Elebook from './Elebook';
import Fileshare from './Fileshare';
import Side from './Side';
const { Header, Content} = Layout;
const items = [
  {
    label: '贴吧',
    key: 'SubMenu',
  },
  {
    label:'电子书',
    key:'book'
  },
  {
    label: '文件分享',
    key: 'fileshare',
  },
];

const HomePage = () => {
  // 搜索框
  const [searchValue, setSearchValue] = useState("");
  const [History, setHistory] = useState([]);
  const handleSearch = () => {
    // 搜索逻辑，将搜索值加入历史记录
    if (searchValue !== "") {
      setHistory([searchValue, ...History]);
      setSearchValue("");
    }
  };
  const handleClearHistory = () => {
    // 清空历史记录
    setHistory([]);
    setSearchValue(""); // 清空输入框的值
  };
  const handleSearchChange = (value) => {
    setSearchValue(value);
  };
  const selectSearchItem = (value) => {
    if (value === "clear") {
      // 点击清空历史记录按钮
      handleClearHistory();
    } else {
      setSearchValue(value);
      handleSearch();
    }
  };
  const options = History.map((item) => ({ value: item }));
  // 添加清空历史记录按钮的选项，只有当历史记录不为空时才显示
  if (History.length > 0) {
    options.push({ value: "clear", label: "清空历史记录" });
  }

  // const {
  //   token: { colorBgContainer },
  // } = theme.useToken();
  const history = useHistory()
  // const HandleCard =()=>{
  //   history.push('/Card')
  // }
  //实现卡片点击喜欢或收藏
  // const [like,setlike] = useState(false)
  // const handleLike=()=>{
  //   setlike(!like)
  // }
  //实现卡片点击收藏
  // const [colect,setColect] = useState(false)
  const [current,setCurrent] =useState('')
  const onhandle=(e)=>{
    setCurrent(e.key)
    if(e.key == 'book'){
      history.push('/home/book')
    }
    else if(e.key == 'fileshare'){
      history.push('/home/fileshare')
    }
    else{
      history.push('/home/posts')
    }
  }
//  //主页面列表
//   const data = Array.from({ length: 23 }).map((_, i) => ({
//     title: `ant design part ${i}`,
//     avatar: `https://xsgames.co/randomusers/avatar.php?g=pixel&key=${i}`,
//     description:
//       '河北师范大学',
//     content:
//       '考研大苏打啊大苏打',
//   }));
  //点击登录
  const click = () => {
    history.push('./login');
  }
  const [postList, setPostList] = useState([]);
  const [loading, setLoading] = useState(true);

  // useEffect(() => {
  //   const fetchData = async () => {
  //     try {
  //       const token =  localStorage.getItem('token'); // Replace this with your actual token value
  //       console.log(token)
  //       const response = await fetch(`http://localhost:2023/api/home-posts-a?token=${token}`);
  //       // const response = await fetch('http://localhost:2023/api/home-posts-a?token=titbit-token 136cfahsxw7oeyis.Isf-obN7lUSekmcMM-F6V1JKj_PAR0RQJUZog_KULbmxhNWmMoRRisl5oMBStKT0BObKdHgCgQolblZ1WZba_LF5uxs9s2x7nB-o4OMZxb3wZxDt8AF9xWilrjXVx4cai8G58Z2mhoSaKY9aHtyzy-yzWo8l08nXNcwsekMmcnkg_zxcfVhkDkRF-azYZulKoPxlnCKsAuw0XobWSJ4kPqcSb5q2uqF7oYu-PsM7qJqm1zwAZGkpBU_wuog5T_wvD3B2Y3kaGDQhcP-Bz-Yz0A');
  //       const data = await response.json();
  //       const convertTimestampToReadable = (timestamp) => {
  //         const date = new Date(timestamp);
  //         return date.toLocaleString(); // 可根据需求使用不同的日期格式化方法
  //       };
  //       setPostList(data.map(post => ({
  //         ...post,
  //         readablePostTime: convertTimestampToReadable(post.post_time),
  //         readableUpdateTime: convertTimestampToReadable(post.update_time)
  //       })));
  //       setLoading(false);
  //     } catch (error) {
  //       console.error('Error fetching post list:', error);
  //       setLoading(false);
  //     }
  //   };

  //   fetchData();
  // }, []);

  return (

    // 主题颜色
    <ConfigProvider
    theme={{
      token: {
        // Seed Token，影响范围大
        colorPrimary: '#73d13d',
        borderRadius: 20,
        // 派生变量，影响范围小
        colorBgContainer: '#f6ffed',
      },
    }}
  >
      <Layout>
        {/* Header头部 */}
        <Layout>
          <Header style={{
              padding: 0, 
              background: '#ffffff',
              margin:10,
              height:130,
              borderRadius:20,
              }}>  
            {
              <div
                style={{display:'flex'}}
              >
            {/* 搜索框 */}  
            <Space direction="vertical" style={{ width: 300,margin:'auto'}}>
                <AutoComplete
                  options={options}
                  value={searchValue}
                  style={{ width: 300 }}
                  onChange={handleSearchChange}
                  onSelect={selectSearchItem}
                  placeholder={"搜索关键字"}
                  backfill={true}
                >
                  <Input
                    suffix={
                      <SearchOutlined
                        onClick={handleSearch}
                        style={{ cursor: "pointer",color:'#73d13d' }}
                      />
                    }
                    value={searchValue}
                    onChange={(e) => setSearchValue(e.target.value)}
                  />
                </AutoComplete>
              </Space>
            {/* 用户 */}  
              <Avatar style={{
                margin:'5px'
              }} size='large' icon={<UserOutlined />}/>  

            {/* 登录 */}
              <Button type="text" onClick={click} style={{marginTop:'10px',marginRight:'10px'}}>登录</Button>
              </div>
            }
          
            {
              <div style={{
                display:'flex',
              }}>
                <Menu 
                style={{
                  height:60,
                  margin:'auto',
                  marginTop:8,
                  borderRadius:20,
                  background:'#ffffff',

                }}
                  mode='horizontal'
                  onClick={onhandle} 
                  selectedKeys={current} 
                  items={items}
                  >
                </Menu>
                <FloatButton.BackTop />
              </div>
            }       
          </Header>
          {/* 内容部分 */}
          <Content
            style={{
              margin: '20px 16px',
              padding: 24,
              minHeight:'75vh',
              background:'#ffffff',
              borderRadius:20,
              maxHeight:'75vh',
              overflow:'auto',
            }}
          >
            <div>
            <Redirect exact from="/home" to="/home/posts" />
            <Route path="/home/posts">
                <Post />
            </Route>
            <Route path='/home/book'>
                <Elebook />
            </Route>
            <Route path='/home/fileshare'>
                <Fileshare />
            </Route>
            </div>
          </Content>
          {/* <Footer style={{ textAlign: 'center', maxHeight:'5vh' }}>
            轻学网
          </Footer> */}
        </Layout>
      </Layout>
    </ConfigProvider>

  );
};


export default HomePage